package cn.tedu.hongbeifang.filters;

import cn.tedu.hongbeifang.security.LoginPrincipal;
import cn.tedu.hongbeifang.web.JsonResult;
import cn.tedu.hongbeifang.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Auther:fzd
 * @Date:2023/3/8
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    //JWT中签名的随机唯一值
    @Value("${csmall.jwt.secret-key}")
    private String secretKey;

    //jwt的最小长度
    public static final int JWT_MIN_LENGTH = 113;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("JWT过滤器开始执行");

        //将SecurityContext中的内容清空,避免【此前携带JWT成功访问后，在接下来的一段时间内不携带JWT也能访问】
        //但一般不使用它
        //SecurityContextHolder.clearContext();

        String jwt = request.getHeader("Authorization");
        log.debug("客户端携带的JWT:{}",jwt);

        if(!StringUtils.hasText(jwt) || jwt.length()<JWT_MIN_LENGTH){
            //如果jwt的内容为空,则放行
            log.debug("客户端没有携带有效的JWT,将放行,由后续的过滤器等组件继续处理此请求");
            filterChain.doFilter(request,response);
            return;
        }
        //尝试去做解析
        Claims cla = null;
        try{
            cla = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
        } catch (MalformedJwtException e){
            String message = "非法访问！";
            log.warn("解析JWT时出现MalformedJwtException，将响应错误消息：{}", message);
            //设置响应到客户端数据的格式
            response.setContentType("application/json; charset=utf-8");
            //创建一个输出流
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_JWT_MALFORMED, message);
            String jsonString = JSON.toJSONString(jsonResult);
            //输出流写出数据
            writer.println(jsonString);
            writer.close();
            return;

        } catch (SignatureException e) {
            String message = "非法访问！";
            log.warn("解析JWT时出现SignatureException，将响应错误消息：{}", message);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_JWT_SIGNATURE, message);
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (ExpiredJwtException e) {
            String message = "您的登录信息已过期，请重新登录！";
            log.warn("解析JWT时出现ExpiredJwtException，将响应错误消息：{}", message);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_JWT_EXPIRED, message);
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (Throwable e) {
            String message = "服务器忙，请稍后再次尝试！（开发过程中，如果看到此提示，请检查控制台的信息，并补充处理异常的方法）";
            log.warn("解析JWT时出现Throwable，将响应错误消息：{}", message);
            log.warn("异常类型：{}", e.getClass());
            log.warn("异常信息：{}", e.getMessage());
            e.printStackTrace(); // 打印异常的跟踪信息，主要是为了在开发阶段更好的检查出现异常的原因
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_UNKNOWN, message);
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        }

        Long id = cla.get("id",Long.class);
        String username = cla.get("username",String.class);
        //权限
        String authoritiesJsonString = cla.get("authoritiesJsonString",String.class);
        log.debug("解析JWT结束，id={}，username={},authoritiesJsonString={}", id, username,authoritiesJsonString);

        //创建LoginPrincipal类型
        LoginPrincipal loginPrincipal = new LoginPrincipal();
        loginPrincipal.setId(id);
        loginPrincipal.setUsername(username);


        //处理认证中的权限
        List<SimpleGrantedAuthority> authorities = JSON.parseArray(authoritiesJsonString, SimpleGrantedAuthority.class);
        log.debug("将JWT中的权限列表中的JSON字符串解析为List<SimpleGrantedAuthority>类型,结果:{}",authorities);

        // 创建Authentication(认证信息)对象
        Object principal = loginPrincipal;
        Object credentials = null;
        Authentication authentication = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);

        // 将Authentication对象存入到SecurityContext中
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        log.debug("已经");

        filterChain.doFilter(request,response);

    }
}
